package com.example.emos.api.service.impl;

import cn.hutool.core.map.MapUtil;
import com.example.emos.api.common.util.PageUtils;
import com.example.emos.api.db.dao.TbLeaveDao;
import com.example.emos.api.db.pojo.TbLeave;
import com.example.emos.api.exception.EmosException;
import com.example.emos.api.service.LeaveService;
import com.example.emos.api.task.LeaveWorkflowTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @author jl
 * @since 2021/11/5 20:39
 */
@Service
public class LeaveServiceImpl implements LeaveService {
    @Autowired
    private TbLeaveDao tbLeaveDao;
    @Autowired
    private LeaveWorkflowTask leaveWorkflowTask;

    @Override
    public PageUtils searchLeaveByPage(HashMap param) {
        ArrayList<HashMap> list = tbLeaveDao.searchLeaveByPage(param);
        long count = tbLeaveDao.searchLeaveCount(param);
        Integer start = MapUtil.getInt(param, "start");
        Integer length = MapUtil.getInt(param, "length");
        return new PageUtils(list, count, start, length);
    }

    @Override
    public boolean searchContradiction(HashMap param) {
        long count = tbLeaveDao.searchContradiction(param);
        return count > 0;
    }

    @Override
    @Transactional
    public int inset(TbLeave leave) {
        int rows = tbLeaveDao.inset(leave);
        // 开启工作流
        if (rows == 1) {
            leaveWorkflowTask.startLeaveWorkflow(leave.getId(), leave.getUserId(), leave.getDays());
        } else {
            throw new EmosException("会议添加失败");
        }
        return rows;
    }

    @Override
    public int deleteLeaveById(HashMap param) {
        Integer id = MapUtil.getInt(param, "id");
        String instanceId = tbLeaveDao.searchInstanceById(id);
        int rows = tbLeaveDao.deleteLeaveById(param);
        if (rows == 1) {
            // 删除工作流
            leaveWorkflowTask.deleteLeaveWorkflow(instanceId, "员工请假", "删除请假申请");
        } else {
            throw new EmosException("删除请假申请失败");
        }
        return rows;
    }

    @Override
    public HashMap searchLeaveById(HashMap param) {
        return tbLeaveDao.searchLeaveById(param);
    }
}
